import {UserInfoAction} from "@/stores/actions/userInfoActions";
import {setLStorage} from "@/utils/auth";
import {LocalStorageEnum} from "@/enums/LocalStorageEnum";

type UserGenderEnum = 'MALE' | 'FEMALE';

export interface IUserInfo {
    userId?: string;
    userName?: string;
    nickName?: string;
    avatar?: string;
    sex?: string;
    email?: string;
    gender?: UserGenderEnum;
    address?: string;
    phonenumber?: string;
    dept?: any;
    roles?: any[];

    [key: string]: any
}

export interface IUserInfoState {
    permissions: string[],
    roles: string[],
    user: IUserInfo
}

type MenuItemMeta = {
    title: string;
    icon: string;
    noCache: boolean;
    link: string;
};

export type IRoutersMenuItem = {
    alwaysShow?: boolean;
    children?: IRoutersMenuItem[];
    component?: string;
    hidden?: boolean;
    meta: MenuItemMeta;
    title: string;
    path: string;
    redirect?: string;
    [key: string]: any;
};

export interface IUserInfoReducersState {
    userInfo?: IUserInfoState
    routerList?: IRoutersMenuItem[]
}

const initialState: IUserInfoReducersState = {
    userInfo: {
        permissions: [],
        roles: [],
        user: {}
    },
    routerList: []
}

const userInfoReducer = (state: IUserInfoReducersState = initialState, action: UserInfoAction) => {
    switch (action.type) {
        case "GETUSERINFO":
            return state
        case "GETUSERINFOSUCCESS":
            setLStorage(LocalStorageEnum.PERMISSIONS, JSON.stringify(action.payload.permissions))
            setLStorage(LocalStorageEnum.ROLES, JSON.stringify(action.payload.roles))
            setLStorage(LocalStorageEnum.USERINFO, JSON.stringify(action.payload.user))
            return {
                ...state,
                userInfo: action.payload
            }
        case "GETROUTERS":
            return state
        case "GETROUTERSSUCCESS":
            setLStorage(LocalStorageEnum.MENU, JSON.stringify(action.payload))
            setTimeout(() => {
                window.location.replace(`${process.env.PUBLIC_URL}/`)
            }, 0)
            return {
                ...state,
                routerList: action.payload
            }
        default:
            return state
    }
}

export default userInfoReducer